package io.wit.modules.sys.controller;

import io.wit.common.annotation.SysLog;
import io.wit.common.utils.PageUtils;
import io.wit.common.utils.Query;
import io.wit.common.utils.R;
import io.wit.common.validator.Assert;
import io.wit.common.validator.ValidatorUtils;
import io.wit.common.validator.group.AddGroup;
import io.wit.common.validator.group.UpdateGroup;
import io.wit.config.ConfigFile;
import io.wit.modules.sys.dao.SysRoleDao;
import io.wit.modules.sys.entity.SysRoleEntity;
import io.wit.modules.sys.entity.SysUserEntity;
import io.wit.modules.sys.service.SysUserService;
import io.wit.modules.sys.shiro.ShiroUtils;
import io.wit.tool.ToolClient;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 系统用户
*/
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {

    @Autowired
	private SysUserService sysUserService;

    @Value("${role_value234}")
    private String value234;

    @Value("${role_value1}")
    private long value1;

    @Value("${role_value2}")
    private long value2;

    @Autowired
    private SysRoleDao sysRoleDao;

	/**
	 * 所有用户列表,分为代理商|管理部门|经营主体
	*/
	@RequestMapping("/list")
	@RequiresPermissions("sys:user:list")
	public R list(@RequestParam final Map<String, Object> params){
        final Query query = new Query(params);
        final String userName = getUserName();
        final Long roleId = getRoleId();
        if(ConfigFile.KEY_SUPER.equals(userName) || roleId == value2){
            //查询列表数据
            final List<SysUserEntity> userList = sysUserService.queryListSuperData(query);
            final int total = sysUserService.queryListSuperTotal(query);
            final PageUtils page = new PageUtils(userList,total,query.getLimit(),query.getPage());
            return R.ok().put("page",page);
        }else{
            final Long subjectId = getSubjectId();
            if(subjectId != null){
                final List<SysUserEntity> userList = sysUserService.queryList(query);
                final int total = sysUserService.queryTotal(query);
                final PageUtils page = new PageUtils(userList,total,query.getLimit(),query.getPage());
                return R.ok().put("page",page);
            }else{
                final PageUtils page = new PageUtils(new ArrayList<>(),0,query.getLimit(), query.getPage());
                return R.ok().put("page",page).put("msg","当前账号尚未添加经营主体");
            }
        }
	}
	
	/**
	 * 获取登录的用户信息
	*/
	@RequestMapping("/info")
	public R info(){
	    try {
            return R.ok().put("user",getUser());
	    } catch (final Exception e) {
            return R.create(205,"未登录或登录超时");
	    }
	}
	
	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@RequestMapping("/password")
	public R password(String password, String newPassword){
		Assert.isBlank(newPassword,"新密码不为能空");
		//原密码
		password = ShiroUtils.sha256(password,getUser().getSalt());
		//新密码
		newPassword = ShiroUtils.sha256(newPassword, getUser().getSalt());
		//更新密码
		int count = sysUserService.updatePassword(getUserId(), password, newPassword);
		if(count == 0){
			return R.error("原密码不正确");
		}
		return R.ok("操作成功");
	}
	
	/**
	 * 重置用户密码
	 */
	@SysLog("重置密码")
	@RequestMapping("/resetting")
	@RequiresPermissions("sys:user:resetting")
	public R resetting(final String userId,final String value){
		Assert.isBlank(userId, "账号不为能空");
		//新密码
		final String salt = RandomStringUtils.randomAlphanumeric(20);
		final String password = ShiroUtils.sha256(value, salt);
		//更新密码
		int count = sysUserService.resettingPassword(userId, password,salt);
		if(count == 0){
			return R.error("密码失败！");
		}
        return R.ok("操作成功");
	}
	
	/**
	 * 用户信息
	*/
	@RequestMapping("/info/{userId}")
	@RequiresPermissions("sys:user:info")
	public R info(@PathVariable("userId") Long userId){
		final SysUserEntity user = sysUserService.queryObject(userId);
		return R.ok().put("user", user);
	}

	//审核
	@PostMapping("/check/{userId}")
    @RequiresPermissions("sys:user:update")
	public void check(@PathVariable("userId") Long userId,final HttpServletResponse response){
        ToolClient.responseJson(sysUserService.check(userId),response);
	}
	
	/**
	 * 保存用户
	*/
	@SysLog("保存用户")
	@RequestMapping("/save")
	@RequiresPermissions("sys:user:save")
	public R save(@RequestBody SysUserEntity user){
        if(checkPrivilege()){
            final String userName = getUserName();
            if(!userName.equals(ConfigFile.KEY_SUPER)){
                user.setRoleId(value1);
                final SysRoleEntity sysRoleEntity = sysRoleDao.queryObject(value1);
                user.setRoleName(sysRoleEntity.getRoleName());
            }
            ValidatorUtils.validateEntity(user,AddGroup.class);
            final int rows = sysUserService.save(user);
            return R.execute(rows);
        }else {
            return R.invalidPrivilege();
        }
	}

    private boolean checkPrivilege(){
        final String userName = getUserName();
        if(userName.equals(ConfigFile.KEY_SUPER)){
            return true;
        }
        final Long roleId = getRoleId();
        final String[] roles = this.value234.split(",");
        for(int x = 0; x < roles.length; x++){
            long result = Long.parseLong(roles[x]);
            if(roleId == result){
                return true;
            }
        }
        return false;
    }
	
	/**
	 * 修改用户
	*/
	@SysLog("修改用户")
	@RequestMapping("/update")
	@RequiresPermissions("sys:user:update")
	public R update(@RequestBody SysUserEntity user){
        if(checkPrivilege()){
            final String userName = getUserName();
            if(!userName.equals(ConfigFile.KEY_SUPER)){
                user.setRoleId(value1);
                final SysRoleEntity sysRoleEntity = sysRoleDao.queryObject(value1);
                user.setRoleName(sysRoleEntity.getRoleName());
            }
            ValidatorUtils.validateEntity(user,UpdateGroup.class);
            sysUserService.update(user);
            return R.ok("操作成功");
        }else {
            return R.invalidPrivilege();
        }
	}
	
	/**
	 * 删除用户
	*/
	@SysLog("删除用户")
	@RequestMapping("/delete")
	@RequiresPermissions("sys:user:delete")
	public R delete(@RequestBody Long[] userIds){
		if(ArrayUtils.contains(userIds,1L)){
			return R.error("系统管理员不能删除");
		}
		if(ArrayUtils.contains(userIds,getUserId())){
			return R.error("当前用户不能删除");
		}
		sysUserService.deleteBatch(userIds);
		return R.ok();
	}
}